package playground.fibu.ejb.dao.mysql;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.Query;

import playground.fibu.ejb.dao.AccountDAO;
import playground.fibu.ejb.dao.FibuDAOException;
import playground.fibu.ejb.entity.Account;

public class MySQLAccountDAO implements AccountDAO {

	private static final String PERSISTENCE_UNIT_NAME = "fibu";
	private static EntityManagerFactory factory;

	public MySQLAccountDAO() {
		factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
	}

	@Override
	public void save(Account account)  {
		EntityManager em = factory.createEntityManager();
		em.getTransaction().begin();
		em.persist(account);
		em.getTransaction().commit();
		em.close();

	}

	@Override
	public void delete(Account account)  {
		// TODO Auto-generated method stub

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Account> findAll() throws FibuDAOException {
		EntityManager em = factory.createEntityManager();
		Query query = em.createQuery("select a from Account a");
		try {
			return (List<Account>) query.getResultList();
			
		} catch (NoResultException e) {
			throw new FibuDAOException(e);
		}
	}

	@Override
	public Account findByPrimaryKey(long id) throws FibuDAOException {
		EntityManager em = factory.createEntityManager();
		Query query = em.createQuery("select a from Account a where a.id = ?1");
		query.setParameter(1, id);
		try {
			return (Account) query.getSingleResult();
			
		} catch (NoResultException e) {
			throw new FibuDAOException(e);
		}
	}

	@Override
	public Account findByName(String accName) throws FibuDAOException {
		EntityManager em = factory.createEntityManager();
		Query query = em
				.createQuery("select a from Account a where a.accountName = ?1");
		query.setParameter(1, accName);
		
		
		try {
			return(Account) query.getSingleResult();
			
		} catch (NoResultException e) {
			throw new FibuDAOException(e);
		}
	}

}
